package com.ldw.chapter4.config;

import com.ldw.chapter4.exception.VerificationCodeException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 4.2.3实现图形验证码的AuthenticationProvider
 * <p>Title: MyAuthenticationProvider2</p>
 * <p>Description: </p>
 *
 * @author: dwLiu
 * @date: 2020/3/22 16:01
 */
@Component
public class MyAuthenticationProvider3 extends DaoAuthenticationProvider {

    /**
     * 把构造方法注入UserDetailsService和PasswordEncoder
     *
     * @param userDetailsService
     * @param passwordEncoder
     */
    public MyAuthenticationProvider3(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder) {
        this.setUserDetailsService(userDetailsService);
        this.setPasswordEncoder(passwordEncoder);
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        //调用父类方法完成密码验证
        super.additionalAuthenticationChecks(userDetails, authentication);
        //获取详细信息
        MyWebAuthenticationDetails details = (MyWebAuthenticationDetails) authentication.getDetails();
        //一旦发现验证码不正确，就立刻抛出相应异常信息
        if (!details.isImageCodeIsRight()) {
            throw new VerificationCodeException();
        }
    }

}
